#!/bin/sh

current_dir=$(pwd)
package_dir="."
mkdir ~/opencv_build


if [ ! -d ""$package_dir"" ];then
  echo "\033[31m[ERROR]: $package_dir not exist!: \033[0m"
  exit 1
fi


# 更新系统包列表
sudo apt update
# 安装基本编译工具链和依赖项
sudo apt install -y build-essential cmake git pkg-config wget unzip
# 安装常用图像格式支持
sudo apt install -y libjpeg-dev libpng-dev libtiff-dev
# 视频功能相关
sudo apt install -y libavcodec-dev libavformat-dev libswscale-dev libv4l-dev
sudo apt install -y libxvidcore-dev libx264-dev
# GUI 支持 (HighGui)
sudo apt install -y libgtk-3-dev
# 可选：优化加速库
sudo apt install -y libatlas-base-dev gfortran libopenblas-dev liblapack-dev


wget http://59.110.144.11/download/opencv/opencv-4.11.0.zip
wget http://59.110.144.11/download/opencv/opencv_contrib-4.11.0.zip
wget http://59.110.144.11/download/opencv/opencv_cache-4.11.0.zip


echo "\033[32m[INFO]:\033[0m unzip opencv-4.11.0.zip ..."
unzip  -q -o $package_dir/opencv-4.11.0.zip -d ~/opencv_build

echo "\033[32m[INFO]:\033[0m unzip opencv_contrib-4.11.0.zip ..."
unzip  -q -o $package_dir/opencv_contrib-4.11.0.zip -d ~/opencv_build

echo "\033[32m[INFO]:\033[0m unzip opencv_cache-4.11.0.zip ..."
unzip  -q -o $package_dir/opencv_cache-4.11.0.zip -d ~/opencv_build


sudo rm opencv-4.11.0.zip
sudo rm opencv_contrib-4.11.0.zip
sudo rm opencv_cache-4.11.0.zip

cd ~/opencv_build/opencv-4.11.0
mkdir .cache

cp -r ~/opencv_build/opencv_cache-4.11.0/* ~/opencv_build/opencv-4.11.0/.cache/

mkdir build
cd build

case $(uname -m) in
  x86_64)
    echo "Intel/AMD 64-bit";
    cmake -D CMAKE_BUILD_TYPE=Release \
          -D WITH_CUDA=OFF \
          -D CMAKE_EXE_LINKER_FLAGS="-lcurl" \
          -D CMAKE_SHARED_LINKER_FLAGS="-lcurl" \
          -D OPENCV_ENABLE_NONFREE=ON \
          -D CMAKE_INSTALL_PREFIX=/usr/local \
          -D OPENCV_EXTRA_MODULES_PATH=../../opencv_contrib-4.11.0/modules ..;
    ;;
  aarch64|arm64)
    echo "ARM 64-bit";
    cmake -D CMAKE_BUILD_TYPE=Release \
          -D WITH_CUDA=OFF \
          -D OPENCV_ENABLE_NONFREE=ON \
          -D CMAKE_INSTALL_PREFIX=/usr/local \
          -D OPENCV_EXTRA_MODULES_PATH=../../opencv_contrib-4.11.0/modules ..;
    ;;
  *)
    echo "Unknown architecture: $(uname -m)";
    ;;
esac

make -j2
sudo make install

cd
sudo rm -r ~/opencv_build
cd ${current_dir}

